class ActivitiesController < ApplicationController
  before_action :authorized, only: %i[likeit joinact new create edit update myact update delete_act
                                      edit_comment push_comment destroy_comment]

  # 良哥写的逻辑没什么变动，主要是改了几个方面。
  # 首先输入端以前段调用的函数和传入的数据为准，通过params中给的id定位活动 @activity = Activity.find(params[:id])
  # 当前用户通过解码token获取 current_user = User.find_by( id: decoded_token[0]['user_id'] )
  # 出现其他用户的场景，需要通过params中的user_id定位
  # 所有的输出改为json格式。默认设置一个error_code字段用于标识执行是否成功，0为成功。后续可约定为错误码。
  # message字段用于传输一些说明文本，比如错误信息等。

  def activity_params
    # define the allowed activity paramsmeter
    params.require(:activity).permit(:title, :from, :to, :starttime, :endtime, :typ_e, :currents, :sum, :description)
  end

  # 接口测试完成
  def sortclass
    # used for sort class by update time
    @activity = Activity.all
    @activity = @activity.order(updated_at: :desc)
    render json: { error_code: 0, activities: @activity }
  end

  # 接口测试完成
  # 良哥本来分了5类活动查询。现在可以从传入的参数中获取活动类型，共用一个函数就可以了。
  def showclass
    @activity = Activity.where(typ_e: params[:typ_e]).order(updated_at: :desc)
    render json: { error_code: 0, activities: @activity }
  end

  # 接口测试完成
  # 显示其他类别
  def showclass_other
    @activity = Activity.where.not(typ_e: %w[运动 出行]).order(updated_at: :desc)
    render json: { error_code: 0, activities: @activity }
  end

  # 接口测试完成
  # 显示活动
  def show
    @activity = Activity.find_by(id: params[:activity_id])
    if @activity.nil?
      render json: { error_code: 1, message: "activity id = #{params[:activity_id]} not found." }
      return
    end
    render json: { error_code: 0, activity: @activity }
  end

  # 接口测试完成
  # 点赞，现在可以重复点赞......
  def likeit
    @activity = Activity.find_by(id: params[:activity_id])
    if @activity.nil?
      render json: { error_code: 1, message: "activity id = #{params[:activity_id]} not found." }
      return
    end
    @activity.likes = String(Integer(@activity.likes) + 1)
    @activity.save
    render json: { error_code: 0, activity: @activity, message: 'likeit successfully!' }
  end

  # 接口测试完成
  # 加入活动
  def joinact
    @activity = Activity.find_by(id: params[:activity_id])
    if @activity.nil?
      render json: { error_code: 1, message: "activity id = #{params[:activity_id]} not found." }
      return
    end
    current_user = User.find_by(id: decoded_token[0]['user_id'])
    if @activity.users.include?(current_user)
      render json: { error_code: 1, activity: @activity, user: current_user,
                     message: "you have joined #{@activity.title}." }
    elsif @activity.currents >= @activity.sum
      render json: { error_code: 1, activity: @activity, user: current_user, message: "#{@activity.title} was full." }
    else
      @activity.currents = (Integer(@activity.currents) + 1).to_s
      @activity.likes += 1
      @activity.users << current_user
      @activity.save
      current_user.save
      render json: { error_code: 0, activity: @activity, user: current_user,
                     message: "#{@activity.title} was successfully joined." }
    end
  end

  # 接口测试完成
  # 最火排序
  def recommendation
    # used for activity recommendation
    @activity = Activity.all
    @activity = @activity.sort_by { |u| 65_535 - Integer(u.likes) }
    render json: { error_code: 0, activities: @activity }
  end

  # 接口测试完成
  # 显示全部活动
  def index
    @activity = Activity.all
    if @activity
      @activity = @activity.order(id: :desc)
      render json: { error_code: 0, activities: @activity }
    else
      render json: { error_code: 1, message: 'No Activity Found' }
    end
  end

  # 无需测试
  def new
    # default: render 'new' template
  end

  # 接口测试完成
  # 创建新活动
  def create
    # used to created a new activity
    # act_hash = JSON.parse params[:activity]
    # @activity = Activity.new(params[:activity])

    # 暂时还没找到快速获取json数据到activity的方法，我对activity的哈希结构不是很了解。先用笨办法跑通
    @activity = Activity.new
    @activity.title = params[:title]
    @activity.from = params[:from]
    @activity.to = params[:to]
    @activity.starttime = params[:starttime]
    @activity.endtime = params[:endtime]
    @activity.typ_e = params[:typ_e]
    @activity.currents = params[:currents]
    @activity.sum = params[:sum]
    @activity.description = params[:description]

    current_user = User.find_by(id: decoded_token[0]['user_id'])
    @activity.creator = Integer(current_user.id)
    @activity.likes = 0
    if @activity.save
      current_user.activities << @activity
      @activity.save
      render json: { error_code: 0, activity: @activity, user: current_user,
                     message: "#{@activity.title} was successfully created." }
    else
      render json: { error_code: 1, activity: @activity, user: current_user,
                     message: "#{@activity.title} create unsuccessfully." }
    end
  end

  # 接口测试完成
  # 控制用户是否允许进入更新页面
  def edit
    @activity = Activity.find_by(id: params[:activity_id])
    if @activity.nil?
      render json: { error_code: 1, message: "activity id = #{params[:activity_id]} not found." }
      return
    end
    current_user = User.find_by(id: decoded_token[0]['user_id'])
    if Integer(@activity.creator) != current_user.id && current_user.root != 0
      render json: { error_code: 1, activity: @activity, user: current_user,
                     message: "you have no right to change #{@activity.title}." }
    else
      render json: { error_code: 0, activity: @activity, user: current_user,
                     message: "you have right to change #{@activity.title}, please go on." }
    end
  end

  # 接口测试完成
  # 控制用户是否可以保存活动内容修改
  def update
    @activity = Activity.find_by(id: params[:id])
    if @activity.nil?
      render json: { error_code: 1, message: "activity id = #{params[:id]} not found." }
      return
    end
    current_user = User.find_by(id: decoded_token[0]['user_id'])
    if Integer(@activity.creator) != current_user.id && current_user.root != 0
      render json: { error_code: 1, activity: @activity, user: current_user,
                     message: "you have no right to change #{@activity.title}." }
    elsif @activity.currents > Integer(params[:sum])
      render json: { error_code: 1, activity: @activity, user: current_user,
                     message: "you can't set sum less than currents." }
    else
      @activity.update(activity_params)
      render json: { error_code: 0, activity: @activity, user: current_user,
                     message: "#{@activity.title} was successfully updated." }
    end
  end

  # 接口测试完成
  # 显示用户的活动
  def user_acts
    current_user = User.find_by(username: params[:username])
    @activity = current_user.activities.all
    render json: { error_code: 0, activities: @activity }
  end

  # 接口测试完成
  # 离开活动
  def leaveact
    @activity = Activity.find_by(id: params[:activity_id])
    if @activity.nil?
      render json: { error_code: 1, message: "activity id = #{params[:activity_id]} not found." }
      return
    end
    current_user = User.find_by(id: decoded_token[0]['user_id'])
    if current_user.activities.include?(@activity)
      current_user.activities.delete(@activity)
      @activity.users.delete(current_user)
      @activity.currents = (Integer(@activity.currents) - 1).to_s
      @activity.save
      current_user.save
      render json: { error_code: 0, activity: @activity, user: current_user,
                     message: "leave #{@activity.title} successfully." }
    else
      render json: { error_code: 1, activity: @activity, user: current_user,
                     message: "You are not in #{@activity.title}, please join." }
    end
  end

  # 接口测试完成
  # 显示参加这个活动的所有用户
  def users
    @activity = Activity.find(params[:activity_id])
    @user = @activity.users.all
    render json: { error_code: 0, users: @user }
  end

  # 接口测试完成
  # 显示用户信息
  def userdetail
    @user = User.find(params[:user_id])
    render json: { error_code: 0, user: @user }
  end

  # 接口测试完成
  # 删除活动
  def delete_act
    @activity = Activity.find_by(id: params[:activity_id])
    if @activity.nil?
      render json: { error_code: 1, message: "activity id = #{params[:activity_id]} not found." }
      return
    end
    current_user = User.find_by(id: decoded_token[0]['user_id'])
    if Integer(@activity.creator) == current_user.id || current_user.root == 0
      @activity.destroy
      render json: { error_code: 0, activity: @activity, user: current_user,
                     message: "Activity '#{@activity.title}' deleted." }
    else
      render json: { error_code: 1, activity: @activity, user: current_user,
                     message: "you have no right to delete #{@activity.title}." }
    end
  end

  # 查询功能
  # 接口测试完成
  def search
    @activity = Activity.where('title LIKE :search OR description LIKE :search', search: "%#{params[:search]}%")
    render json: { error_code: 0, activities: @activity }
  end

  # 发布评论
  def push_comment
    # begin
    @comment = Comment.new
    @comment.content = comment_params[:content]

    logged_in_user
    activity = Activity.find_by_id(comment_params[:activity_id])

    @user.comments << @comment
    activity.comments << @comment
    if @comment.save
      render json: { error_code: 0, comment: @comment, message: 'Posting comment successfully.' }
    else
      render json: { error_code: 1 }
      # render json: { error_code: 1, message: 'Posting comment failed.'}
    end
  end

  # 展示评论
  def show_comments
    @activity = Activity.find_by_id(params[:activity_id])
    if @activity
      @comments = @activity.comments
      if @comments.to_s.nil?
        render json: { error_code: 1, message: 'No comments.' }
      else
        render json: { error_code: 0, comments: @comments }
      end
    else
      render json: { error_code: 1, message: 'Activity Not Found' }
    end
  end

  # 编辑评论
  def edit_comment
    @comment = Comment.find_by_id(params[:comment_id])
    logged_in_user
    if @user.id == @comment.user.id && @comment.update(content: comment_params[:content])
      render json: { error_code: 0,  message: 'Update successfully.' }
    else
      render json: { error_code: 1,  message: 'Updating failed.' }
    end
  end

  # 删除评论
  def destroy_comment
    logged_in_user
    @comment = Comment.find_by_id(params[:comment_id])
    if @user.id == @comment.user.id || @user.root == 0
      @comment.destroy
      render json: { error_code: 0, message: 'Destroy successfully.' }
    else
      render json: { error_code: 1, message: 'Destroying failed.' }
    end
  end

  def comment_params
    params.permit(:content, :activity_id)
  end
end
